package com.zxq.web.assist;

import com.zxq.web.controller.IOTProductController;
import com.zxq.web.dto.PlatformProjectDTO;
import com.zxq.web.iot.domain.IotProject;
import com.zxq.web.iot.service.impl.IotProjectServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ExpireCheckServer implements Runnable {


    @Autowired
    IOTProductController iotProductController;

    @Autowired
    IotProjectServiceImpl projectServiceImpl;

    @Override
    public void run() {
        List<IotProject> iotProductDos = projectServiceImpl.selectIotProjectList(new IotProject());
        log.info("expire device number:" + iotProductDos.size());
        iotProductDos.forEach(iotProductDo -> {
            Date date = iotProductDo.getStartTime();
            Long timeLimit = iotProductDo.getDays() * 24 * 60 * 60 * 1000L;
            Long byTime = date.getTime() + timeLimit;
            if(System.currentTimeMillis() > byTime) {
                PlatformProjectDTO productDTO = new PlatformProjectDTO();
                productDTO.setProjectId(iotProductDo.getId());
                productDTO.setOperatorId(iotProductDo.getCreator());
                log.info(String.format("expire product: {0} ",iotProductDo.getId()));
                iotProductController.stopProductServer(productDTO);
            }
        });
    }

    @PostConstruct
    public void periodExecute() {
        log.info("scan expire device!");
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(2);
        executorService.scheduleAtFixedRate(this ,0,1, TimeUnit.HOURS);
    }




}
